package com.team8.upload.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.team8.common.results.PageResult;
import com.team8.upload.config.XmlPathConfig;
import com.team8.upload.dao.UploadDao;
import com.team8.upload.pojo.XmlFiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@EnableConfigurationProperties(XmlPathConfig.class)
public class UploadService {

    @Autowired
    private XmlPathConfig xmlPathConfig;

    @Autowired
    private UploadDao uploadDao;

    private static final List<String> CONTENT_TYPES = Arrays.asList("application/xml", "text/xml");

    private static final List<String> MSG_TYPE = Arrays.asList("BASE-APUE", "DFME-BLLS", "DFME-CKLS", "DFOE-DFDL");

    private static final Random random = new Random();

    public String upload(MultipartFile file) {

        String filename = file.getOriginalFilename();
        // 校验文件的类型
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            return "bad file type!   - >   " + filename;
        }
        String type = filename.substring(0, 9);
        if(!MSG_TYPE.contains(type)){
            return "bad msg type!   - >   " + filename;
        }
        try {

            Example example = new Example(XmlFiles.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("fileName", filename);
            List<XmlFiles> xmlFiles1 = uploadDao.selectByExample(example);

            if(!CollectionUtils.isEmpty(xmlFiles1)){
                return "bad file! file existed   - >   " + filename;
            }


            int randomInt = random.nextInt(100);

            // 最后面不包含分隔符
            String pathParent = xmlPathConfig.getRoot() +  File.separator + randomInt + File.separator + type;
            String urlParent = xmlPathConfig.getPrefixUrl() + "/" + randomInt + "/" + type;

            File parent = new File(pathParent);

            if(!parent.exists())
                parent.mkdirs();

            String path = pathParent + File.separator + filename;
            System.out.println(path);

            file.transferTo(new File(path));
            XmlFiles xmlFiles = new XmlFiles();
            xmlFiles.setFileType(type);
            xmlFiles.setStatus("0");
            xmlFiles.setFileName(filename);
            xmlFiles.setUploadTime(new Date());
            String url = urlParent+ "/" + filename;
            xmlFiles.setFilePath(url);
            uploadDao.insert(xmlFiles);

            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "unkown error!   - >   " + filename;
    }

    public Boolean updateXmlFileStatus(String filename, String status) {

        Example example = new Example(XmlFiles.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("fileName", filename);

        List<XmlFiles> xmlFiles = uploadDao.selectByExample(example);

        if(CollectionUtils.isEmpty(xmlFiles)){
            return false;
        }

        XmlFiles xmlFile = xmlFiles.get(0);
        xmlFile.setHandleTime(new Date());
        xmlFile.setStatus(status);
        uploadDao.updateByExample(xmlFile, example);
        return true;

    }

    public PageResult<XmlFiles> getXmlInfos(Integer page, Integer size) {
//        SELECT * FROM xml_files ORDER BY upload_time DESC;
        PageHelper.startPage(page, size);
        Example example = new Example(XmlFiles.class);

        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("upload_time DESC");
        Page<XmlFiles> xmlFiles = (Page<XmlFiles>)uploadDao.selectByExample(example);
        PageResult<XmlFiles> pageResult = new PageResult<>(xmlFiles.getTotal(), xmlFiles.getResult());
        return pageResult;
    }
}